package android.pot.com.smartcar.ui.home.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.pot.com.smartcar.R;
import android.pot.com.smartcar.action.Action;
import android.pot.com.smartcar.base.CommonRecycleAdapter;
import android.pot.com.smartcar.base.MyResponseHandler;
import android.pot.com.smartcar.base.RecycleViewHolder;
import android.pot.com.smartcar.base.swipe.SwipeBackActivity;
import android.pot.com.smartcar.entity.AreaEntity;
import android.pot.com.smartcar.entity.ShopListEntity;
import android.pot.com.smartcar.entity.UserInfo;
import android.pot.com.smartcar.tool.LoadingTool;
import android.pot.com.smartcar.tool.LocationHelper;
import android.pot.com.smartcar.util.GsonUtil;
import android.pot.com.smartcar.util.PermissionUtil;
import android.pot.com.smartcar.widget.ActionSheetDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by zhaoshilu on 2017/11/27.
 */
public class ShopListActivity extends SwipeBackActivity implements  EasyPermissions.PermissionCallbacks, LocationHelper.LocationCallBack {

    private RefreshLayout refreshLayout;

    private RecyclerView mRecyclerView;

    private EditText et_search;

    private TextView tv_type,tv_area;

    private TextView tv_title;

    private View ll_empty_view;

    private CommonRecycleAdapter mAdapter;

    private int curPage = 1;

    private int pageCount;

    private int page;

    private boolean showLoading = true;

    private List<ShopListEntity.ShopListData> mDatas = new ArrayList<>();

    private int shopType = -1;

    private int areaId = -1;

    private AreaEntity areaList;

    private String cid;

    private LocationHelper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_list);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        initView();
        addListener();
        initData();
    }

    @Override
    protected void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        ll_empty_view = findViewById(R.id.ll_empty_view);
        et_search = (EditText) findViewById(R.id.et_search);
        tv_type = (TextView) findViewById(R.id.tv_type);
        tv_area = (TextView) findViewById(R.id.tv_area);
        initListView();
    }

    private void initListView(){
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new CommonRecycleAdapter<ShopListEntity.ShopListData>(this, R.layout.listcell_home_car, mDatas) {
            @Override
            public void convert(RecycleViewHolder helper, final ShopListEntity.ShopListData item) {
//                if (item.getShop_name().length()>17){
//                    helper.setLayoutHeight(R.id.rl_outer,DensityUtil.dp2px(110));
//                    helper.setLayoutHeight(R.id.fl_outer,DensityUtil.dp2px(118));
//
//                }else{
//                    helper.setLayoutHeight(R.id.rl_outer,DensityUtil.dp2px(100));
//                    helper.setLayoutHeight(R.id.fl_outer,DensityUtil.dp2px(108));
//
//                }
                helper.setImageByUrl(R.id.iv_icon,item.getPlan());
                helper.setText(R.id.tv_title,item.getShop_name());
                helper.setText(R.id.tv_site,item.getShop_address());
                helper.setText(R.id.tv_distance,item.getDistance());
                if (item.getCertification_status() == 1){
                    helper.setVisible(R.id.tv_identify,true);
                }else{
                    helper.setVisible(R.id.tv_identify,false);
                }
                helper.setOnClickListener(R.id.rl_outer, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Bundle bundle = new Bundle();
                        bundle.putString("shop_id",item.getId());
                        startAct(ShopListActivity.this, ShopDetailActivity.class,bundle);
                    }
                });

            }
        };

        mRecyclerView.setAdapter(mAdapter);
    }


    @Override
    protected void addListener() {
        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToFinishActivity();
            }
        });
        findViewById(R.id.iv_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shopType = -1;
                areaId = -1;
                tv_area.setText("我的位置");
                tv_type.setText("门店类型");
                mDatas.clear();
                getDetailData();
            }
        });
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //关闭软键盘
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    shopType = -1;
                    areaId = -1;
                    tv_area.setText("我的位置");
                    tv_type.setText("门店类型");
                    mDatas.clear();
                    getDetailData();
                    return true;
                }
                return false;
            }
        });

        findViewById(R.id.rl_area).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mDatas.clear();
                Bundle bundle = new Bundle();
                bundle.putSerializable("data",areaList);
                startActForResult(ShopListActivity.this,AreaSelectActivity.class,bundle);

            }
        });
        findViewById(R.id.tv_default).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shopType = -1;
                areaId = -1;
                et_search.setText("");
                tv_area.setText("我的位置");
                tv_type.setText("门店类型");
                mDatas.clear();
                getDetailData();

            }
        });
        findViewById(R.id.rl_type).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActionSheetDialog dialog = new ActionSheetDialog(ShopListActivity.this)
                        .builder()
                        .setTitle("门店类型")
                        .setCancelable(true)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("默认排序", ActionSheetDialog.SheetItemColor.Red
                                , new ActionSheetDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int po) {
                                        shopType =-1;
                                        tv_type.setText("默认排序");
                                        mDatas.clear();
                                        getDetailData();

                                    }
                                })
                        .addSheetItem("认证店铺", ActionSheetDialog.SheetItemColor.Red
                                , new ActionSheetDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int po) {
                                        shopType =1;
                                        tv_type.setText("认证店铺");
                                        mDatas.clear();
                                        getDetailData();

                                    }
                                })
                     ;
                dialog.show();
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mDatas.clear();
                curPage = 1;
                showLoading = false;
                getDetailData();

            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                curPage++;
                showLoading = false;
                getDetailData();
            }
        });
    }

    private void showPickerView(){
        OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(ShopListActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {

                getDetailData();

            }
        }).build();
//        optionsPickerView.setPicker();
        optionsPickerView.show();
    }

    @Override
    protected void initData() {
        Bundle bundle =  getIntent().getExtras();
        cid= bundle.getString("cid");
        String name = bundle.getString("cname");
        tv_title.setText(name);
        LocationTask();
        initArea();
    }

    private void initArea(){
        Map<String,String> params = new HashMap<>();

        Action.get().area_list(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,JSONObject response) {
                areaList = GsonUtil.getObject(response.toString(), AreaEntity.class);

            }
        });
    }

    private void getDetailData(){
        Map<String,String> params = new HashMap<>();
        params.put("service_cid",cid);
        if (!TextUtils.isEmpty(UserInfo.instance().getLat())) {
            params.put("lat", UserInfo.instance().getLat());
        }
        if (!TextUtils.isEmpty(UserInfo.instance().getLng())) {
            params.put("lng", UserInfo.instance().getLng());
        }
        if (!TextUtils.isEmpty(et_search.getText().toString())){
            params.put("shop_name", et_search.getText().toString());

        }
        if (areaId != -1) {
            params.put("area_id", areaId+"");
        }
        if (shopType != -1) {
            params.put("certification_status", shopType+"");
        }
        params.put("page", curPage+"");
        params.put("limit", "10");

        if (showLoading){
            LoadingTool.StartLoading(this);
        }


        Action.get().shop_list(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,JSONObject response) {
                if (showLoading) {
                    LoadingTool.EndLoading(ShopListActivity.this);
                }
                ShopListEntity entity = GsonUtil.getObject(response.toString(), ShopListEntity.class);
                pageCount = entity.getPage().getPage_count();
                page = entity.getPage().getPage();
                mDatas.addAll(entity.getData());
//                if (mDatas.size()>1){
//                    mDatas.get(1).setShop_name("中国壳牌加油站牌加油站的（高新区）站");
//                }
                handler.sendEmptyMessage(0);




            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                super.onFailure(statusCode, error_msg);
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                if (mDatas.size() < pageCount) {
                    refreshLayout.setEnableLoadMore(true);
                } else {
                    refreshLayout.setEnableLoadMore(false);
                }
            }
        });
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (mDatas.size()>0){
                ll_empty_view.setVisibility(View.GONE);
            }else{
                ll_empty_view.setVisibility(View.VISIBLE);
            }
            mAdapter.notifyDataSetChanged();
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            if (page < pageCount) {
                refreshLayout.setEnableLoadMore(true);
            } else {
                refreshLayout.setEnableLoadMore(false);
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode ==3000){
            areaId = data.getIntExtra("areaId",-1);
            if (areaId == -1){
                tv_area.setText("我的位置");
            }else{
                String areaName = data.getStringExtra("areaName");
                tv_area.setText(areaName);
            }
            mDatas.clear();
            getDetailData();
        }
    }



    @Override
    public void onDestroy() {
        helper.stop();
        super.onDestroy();
    }




    /**
     * 请求位置权限码
     */
    public static final int REQUEST_LOCATION_PERM = 101;

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            PermissionUtil.openPermissionDialog(this,getString(R.string.request_location_permission));

        }
    }

    /**
     * EsayPermissions接管权限处理逻辑
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @AfterPermissionGranted(REQUEST_LOCATION_PERM)
    public void LocationTask() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
            // Have permission, do the thing!
            startLocation();
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, getString(R.string.request_location),
                    REQUEST_LOCATION_PERM, Manifest.permission.ACCESS_COARSE_LOCATION);
        }
    }

    //开启定位

    public void startLocation() {

        helper = LocationHelper.getInstance();

        helper.setCallBack(this);

        helper.start();

    }

    //定位返回的数据
    @Override
    public void callBack(String addr, String streetnumber, final double lat, final double lng, String district, String street, final String city, String province) {

        UserInfo.instance().setLat(lat+"");
        UserInfo.instance().setLng(lng+"");
        getDetailData();


    }
}